//
//  main.c
//  lib-netio
//
//  Created by Alex on 9/27/11.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#include "lib-netio.h"

#include <stdio.h>
#include <arpa/inet.h>


#define READ_BUFSIZE 256


void opened(nconn *);
void readin(nconn *);
void prompt(nconn *);
void closed(nconn *);
void error(nconn *);

void readin(nconn * n)
{
    char inbuf[READ_BUFSIZE];
    ssize_t inSize, totalSize = 0;
    bool promptPrinted = false;
    
    while((inSize = nread(n, inbuf, READ_BUFSIZE-1)))
    {
        if(!promptPrinted) promptPrinted = true | printf("< ");
        inbuf[inSize] = '\0';
        printf("%s", inbuf);
        memset(inbuf, 0, READ_BUFSIZE);
        totalSize += inSize;
    }
    
    if(totalSize) printf("\n");
    
    if(n->open)
        prompt(n);
}

void prompt(nconn * n)
{
    size_t i = 0;
    char outbuf[1024];
    do {
        printf("> ");
        fgets(outbuf+i, 1024, stdin);
        i = strlen(outbuf);
        if(outbuf[i-2] != '\\') {
            strcpy(&outbuf[i-1], "\r\n");
            break;
        }
        strcpy(&outbuf[i-2], "\r\n");
    } while (true);
    nwrite(n, outbuf, strlen(outbuf));
}

void opened(nconn * n)
{
    printf("Connected.\n");
    readin(n);
    return;
}

void closed(nconn * n)
{
    printf("Connection closed.\n");
}

void error(nconn * n)
{
    printf("error: %d", n->error);
}

int main (int argc, const char * argv[])
{
    /*if(argc < 3) {
        printf("Usage: netio [host] [port]\n");
        return 0;
    }*/
    
    printf("End lines with \\ to continue message.\n");
    
    // Open a connection and block until ready for writing.
    // nconn * n = nopen(argv[1], atoi(argv[2]), 10, NULL);
    nconn * n = nopen("8.8.8.8", 53, 3, (ncallbacks){ opened, readin, error, closed } );
    
    if(n)
        nwait(n);
    
    return 0;
    while (true)
    {
        prompt(n);
    }
    
    
    
    
    //nwait(n);
    
    //nlisten(n, cb);
    
    
    /*
    nlisten(n, cb);
    char * str = "GET /\nHost: google.com\n\n";
    nwrite(n, str, strlen(str));
    
    nwait(n);
     */
    
    return 0;
}

